﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;
using EditState = Sunlight.Dispatch.UI.Extensions.EditState;

namespace Sunlight.Dispatch.UI {
    public partial class BusinessSearchFrm : BaseFrm {
        public BusinessSearchFrm() {
            InitializeComponent();
            this.dgvBusinessCategory.ReadOnly = true;
            this.dgvBusinessCategory.AutoGenerateColumns = false;
            this.dgvBusinessCategory.AllowUserToAddRows = false;
            this.dgvBusinessCategory.AllowUserToDeleteRows = false;
            this.dgvBusinessCategory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvBusinessCategory.RowPostPaint += DataGridView_RowPostPaint;

            this.dgvBusinessCategory.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.dgvBusinessCategory.CellContentClick += this.dgvBusinessCategory_CellContentClick;
            this.dgvBusinessCategory.SelectionChanged += this.DgvBusinessCategory_SelectionChanged;
            this.dgvBusinessCategory.MultiSelect = false;
            this.tsTextBox.KeyDown += TsTextBox_KeyDown;
            this.SizeChanged += this.BusinessSearchFrm_SizeChanged;

            this.InitComboBoxForDataBase(this.comboBoxDataBase.ComboBox);
        }

        private void DgvBusinessCategory_SelectionChanged(object sender, EventArgs e) {
            SetItemIsSelected(this.dgvBusinessCategory.CurrentRow);
        }

        private void SetItemIsSelected(DataGridViewRow row) {
            foreach(DataGridViewRow dataGridViewRow in this.dgvBusinessCategory.Rows) {
                if(row.Index == dataGridViewRow.Index) {
                    dataGridViewRow.Cells[0].Value = true;
                    continue;
                }
                dataGridViewRow.Cells[0].Value = false;
            }
        }

        private void BusinessSearchFrm_SizeChanged(object sender, EventArgs e) {
            this.LoadInitLocation();
        }

        private void TsTextBox_KeyDown(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter)
                SearchGridView(default(int) + 1);
        }

        private void tsbSearch_Click(object sender, EventArgs e) {
            SearchGridView(default(int) + 1);
        }

        private void dgvBusinessCategory_CellContentClick(object sender, DataGridViewCellEventArgs e) {
            try {
                if(e.ColumnIndex == 3) {
                    var row = this.dgvBusinessCategory.Rows[e.RowIndex];
                    var linkColumnValue = row.Cells[3].Value;
                    if(linkColumnValue != null && File.Exists(linkColumnValue.ToString())) {
                        Process.Start(linkColumnValue.ToString());
                    }
                }
            } catch(Exception exception) {
                var msg = LoggerUtils.GetExceptionMsg(exception, string.Empty);
                LoggerUtils.Error(msg);
            }
        }

        private void SearchGridView(int pageIndex) {
            this.IsLoading = true;
            if(this.comboBoxDataBase.ComboBox.SelectedItem == null) {
                MessageBoxEx.Show(this, "请选择数据库", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var db = this.comboBoxDataBase.ComboBox.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                IQueryable<TBusiness> result = dataContext.TBusiness;
                if(!string.IsNullOrEmpty(this.tsTextBox.Text)) {
                    var selectedText = this.tsTextBox.Text;
                    result = result.Where(d => d.Code.ToLower().Contains(selectedText.ToLower()) || d.Name.ToLower().Contains(selectedText.ToLower()));
                }

                var recordCount = result.Count();
                var data = result.OrderBy(d => d.ID).ToList();
                data.ForEach(d => {
                    d.LinkText = "查看使用范围";
                    d.IsSelected = false;
                    d.ConnectString = db.ConnectString;
                });
                this.dgvBusinessCategory.DataSource = data;
                this.IsLoading = false;
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e) {
            if(this.dgvBusinessCategory.Rows.Count <= 0)
                return;
            var rows = this.dgvBusinessCategory.Rows.Cast<DataGridViewRow>().Select(d => (TBusiness)d.DataBoundItem).ToList();
            if(rows.All(d => !d.IsSelected)) {
                MessageBoxEx.Show(this, "请选择要删除的数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(rows.Count(d => d.IsSelected) > 1) {
                MessageBoxEx.Show(this, "只能单条进行删除，请重新选择", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(this.comboBoxDataBase.ComboBox.SelectedItem == null) {
                MessageBoxEx.Show(this, "请选择数据库", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var db = this.comboBoxDataBase.ComboBox.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            var item = rows.First(d => d.IsSelected);
            if(item == null)
                return;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                if(dataContext.TFileLog.Any(d => d.BusinessCode == item.Code) || dataContext.RunningLog.Any(d => d.BusinessCode == item.Code) || dataContext.TIntf.Any(d => d.BusinessCode == item.Code)) {
                    DialogResult dialogResult = MessageBoxEx.Show(this, "该分类已经被使用，不能删除，只能修改名称，是否修改？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if(dialogResult == DialogResult.OK) {
                        var frm = new BusinessInsertFrm(EditState.编辑, item);
                        frm.MdiParent = this.MdiParent;
                        frm.EditSubmitted += Frm_EditSubmitted;
                        frm.Show();
                    }
                    return;
                }

                var deletedItem = dataContext.TBusiness.FirstOrDefault(d => d.ID == item.ID);
                if(deletedItem == null)
                    return;
                dataContext.TBusiness.DeleteOnSubmit(deletedItem);
                dataContext.SubmitChanges();
            }

            this.SearchGridView(1);
        }

        private void tsbInsert_Click(object sender, EventArgs e) {
            var frm = new BusinessInsertFrm(EditState.新增, null);
            frm.MdiParent = this.MdiParent;
            frm.EditSubmitted += Frm_EditSubmitted;
            frm.Show();
        }

        private void Frm_EditSubmitted(object sender, SubmittedEventArgs e) {
            e.Close();
            this.SearchGridView(1);
        }

        private void tsbUpdate_Click(object sender, EventArgs e) {
            if(this.dgvBusinessCategory.Rows.Count <= 0)
                return;
            var rows = this.dgvBusinessCategory.Rows.Cast<DataGridViewRow>().Select(d => (TBusiness)d.DataBoundItem).ToList();
            if(rows.All(d => !d.IsSelected)) {
                MessageBoxEx.Show(this, "请选择要删除的数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(rows.Count(d => d.IsSelected) > 1) {
                MessageBoxEx.Show(this, "只能单条进行删除，请重新选择", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var item = rows.First(d => d.IsSelected);
            if(item == null)
                return;
            var frm = new BusinessInsertFrm(EditState.编辑, item);
            frm.MdiParent = this.MdiParent;
            frm.EditSubmitted += Frm_EditSubmitted;
            frm.Show();
        }
    }
}
